#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017-09-29 18:51:24
# @Author  : WUQINGLONG
# @Contact : 1603763721@qq.com

# =======================================
# 优美胜于丑陋（Python 以编写优美的代码为目标）
# 明了胜于晦涩（优美的代码应当是明了的，命名规范，风格相似）
# 简洁胜于复杂（优美的代码应当是简洁的，不要有复杂的内部实现）
# 复杂胜于凌乱（如果复杂不可避免，那代码间也不能有难懂的关系，要保持接口简洁）
# 扁平胜于嵌套（优美的代码应当是扁平的，不能有太多的嵌套）
# 间隔胜于紧凑（优美的代码有适当的间隔，不要奢望一行代码解决问题）
# 可读性很重要（优美的代码是可读的）
# =======================================

"""
功能描述：
    1.学习使用semaphore

"""

from atexit import register
from random import randrange
from threading import BoundedSemaphore, Lock, Thread
from time import sleep, ctime

lock = Lock()
MAX = 5
candytray = BoundedSemaphore(MAX)


def refill():
    lock.acquire()
    print('Refilling candy...')
    try:
        candytray.release()
    except ValueError:
        print('full, skipping')
    else:
        print('OK')
    lock.release()


def buy():
    lock.acquire()
    print('Buying candy...')
    if candytray.acquire(False):
        print('OK')
    else:
        print('empyt, skipping')
    lock.release()


def producer(loops):
    index = 0
    while index < loops:
        index += 1
        refill()
        sleep(randrange(3))


def consumer(loops):
    index = 0
    while index < loops:
        index += 1
        buy()
        sleep(randrange(3))


def main():
    print('starting at:', ctime())
    loops = randrange(2, 6)
    print('THE CANDY MACHINE (full with %d bars)!' % MAX)
    Thread(target=consumer, args=(randrange(loops, loops + MAX * 2),)).start()
    Thread(target=producer, args=(loops,)).start()


@register
def _atexit():
    print('all DONE at:', ctime())


if __name__ == '__main__':
    main()
